package com.inspur.jzsxxzx.controller.muluzhili;

import com.inspur.jzsxxzx.entity.muluzhili.UpDataCatalog;
import com.inspur.jzsxxzx.entity.muluzhili.UpDataCatalogItem;
import com.inspur.jzsxxzx.entity.muluzhili.UpDataReconciliation;
import com.inspur.jzsxxzx.service.muluzhili.UpDataCatalogItemService;
import com.inspur.jzsxxzx.service.muluzhili.UpDataCatalogService;
import com.inspur.jzsxxzx.service.muluzhili.UpDataReconciliationService;
import com.inspur.jzsxxzx.util.DateUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.ArrayList;

@Controller
@RequestMapping("/updatacatalog")
public class UpDataCatalogController {

    @Autowired
    private UpDataCatalogService upDataCatalogService;

    @Autowired
    private UpDataCatalogItemService upDataCatalogItemService;

    @Autowired
    private UpDataReconciliationService upDataReconciliationService;

    /**
     * 获取上报目录数据，支持分页和条件查询
     *
     * @param page              页码，默认为1
     * @param limit             每页条数，默认为10
     * @param cataTitle         目录标题（模糊查询）
     * @param importedByOrgName 数据提供方名称（模糊查询）
     * @return 分页数据结果
     */
    @GetMapping("/data")
    @ResponseBody
    public Map<String, Object> getUpDataCatalogData(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int limit,
            @RequestParam(required = false) String cataTitle,
            @RequestParam(required = false) String importedByOrgName) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 获取过滤后的数据总数
            int totalCount = upDataCatalogService.countByCondition(cataTitle, importedByOrgName);

            // 分页获取数据
            List<UpDataCatalog> pageData = upDataCatalogService.findPageByCondition(cataTitle, importedByOrgName, page,
                    limit);

            result.put("code", 0);
            result.put("count", totalCount);
            result.put("data", pageData);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "数据加载失败: " + e.getMessage());
        }

        return result;
    }

    @GetMapping("/up-data-catalog-detail")
    public String catalogDetail(@RequestParam Integer id, Model model) {
        // 根据ID获取目录信息
        UpDataCatalog catalog = upDataCatalogService.findById(id);
        model.addAttribute("catalog", catalog);

        // 根据扩展目录ID获取相关信息项列表
        List<UpDataCatalogItem> catalogItems = upDataCatalogItemService.findByExtCataId(catalog.getExtCataId());
        model.addAttribute("catalogItems", catalogItems);
        return "fragments/up-data-catalog-detail";
    }

    /**
     * 根据ID获取单个目录项的详细信息
     * 
     * @param id 目录ID
     * @return 目录项的详细信息
     */
    @GetMapping("/data-item")
    @ResponseBody
    public UpDataCatalog getUpDataCatalogItem(@RequestParam Integer id) {
        return upDataCatalogService.findById(id);
    }

    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateCatalogAndItems(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 从请求参数中构建UpDataCatalog对象
            UpDataCatalog catalog = new UpDataCatalog();
            int id = getIntegerParameter(request, "id");
            // String old_region_code = upDataCatalogService.findById(id).getRegionCode();
            String region_code = request.getParameter("regionCode");
            String cdBatch = request.getParameter("cdBatch");

            String updateCycle = request.getParameter("updateCycle");
            String otherUpdateCycle = request.getParameter("otherUpdateCycle");
            if ("8".equals(updateCycle) && (otherUpdateCycle == null || otherUpdateCycle.trim().isEmpty())) {
                result.put("code", 1);
                result.put("msg", "更新失败: 更新周期为其他时，其他更新周期不能为空！");
                return result;
            }

            String processLevel = request.getParameter("processLevel");
            if (processLevel == null || processLevel.trim().isEmpty()) {
                result.put("code", 1);
                result.put("msg", "处理级别不能为空！");
                return result;
            }

            catalog.setId(id);
            catalog.setBaseCataId(request.getParameter("baseCataId"));
            catalog.setExtCataId(request.getParameter("extCataId"));
            catalog.setExtCataTitle(request.getParameter("extCataTitle"));
            catalog.setBusinessGroupName(request.getParameter("businessGroupName"));
            catalog.setExtCataCode(request.getParameter("extCataCode"));
            catalog.setFieldType(request.getParameter("fieldType"));
            catalog.setFieldTypeName(request.getParameter("fieldTypeName"));
            catalog.setTaskCatalogName(request.getParameter("taskCatalogName"));
            catalog.setTaskCatalogCode(request.getParameter("taskCatalogCode"));
            catalog.setUseLevel(request.getParameter("useLevel"));
            catalog.setDescription(request.getParameter("description"));
            catalog.setExtDataCataCode(request.getParameter("extDataCataCode"));
            catalog.setSharedCondition(request.getParameter("sharedCondition"));
            catalog.setSourceItemName(request.getParameter("sourceItemName"));
            catalog.setSourceItemCode(request.getParameter("sourceItemCode"));
            catalog.setRelationItemName(request.getParameter("relationItemName"));
            catalog.setRelationItemCode(request.getParameter("relationItemCode"));
            catalog.setImportanceLevel(request.getParameter("importanceLevel"));
            catalog.setPocessLevel(request.getParameter("pocessLevel"));
            catalog.setAeraScope(request.getParameter("aeraScope"));
            catalog.setOtherAeraScope(request.getParameter("otherAeraScope"));
            catalog.setTimeRange(request.getParameter("timeRange"));
            catalog.setInternalOrgName(request.getParameter("internalOrgName"));
            catalog.setOrgCode(request.getParameter("orgCode"));
            catalog.setExtDescription(request.getParameter("extDescription"));
            catalog.setUpdateCycle(updateCycle);
            catalog.setOtherUpdateCycle(otherUpdateCycle);
            catalog.setIsPublish(request.getParameter("isPublish"));
            catalog.setNotPublishReason(request.getParameter("notPublishReason"));
            catalog.setRegionName(request.getParameter("regionName"));
            catalog.setRegionCode(region_code);
            catalog.setCatalogType(request.getParameter("catalogType"));
            catalog.setExtCataVersion(request.getParameter("extCataVersion"));
            catalog.setStatus(request.getParameter("status"));
            catalog.setCdBatch(cdBatch);

            // 设置更新时间
            Date now = new Date();
            catalog.setUpdateTime(now);
            catalog.setCdTime(now);

            // 更新目录信息
            upDataCatalogService.update(catalog);

            // 处理信息项
            // int item_size = 0;
            List<UpDataCatalogItem> items = parseCatalogItems(request);
            if (!items.isEmpty()) {
                // item_size = items.size();
                for (UpDataCatalogItem item : items) {
                    item.setCdTime(now);
                    upDataCatalogItemService.update(item);
                }
            }

            // 统计信息只计算市级，不区分各区县，所以删除这里的逻辑
            // if (!old_region_code.equals(region_code)) {
            // int reconclition_maxId = upDataReconciliationService.findMaxId() == null ? 1
            // : upDataReconciliationService.findMaxId() + 1;
            // List<UpDataReconciliation> udr_list = upDataReconciliationService
            // .findByRegionCodeAndCdBatch("up_data_catalog", old_region_code, cdBatch);
            // if (udr_list != null && udr_list.size() > 0) {
            // UpDataReconciliation udr = udr_list.get(0);
            // udr.setCdCount(String.valueOf(Integer.parseInt(udr.getCdCount()) - 1));
            // udr.setUpdateTime(now);
            // udr.setCdTime(now);
            // upDataReconciliationService.update(udr);
            // }

            // udr_list =
            // upDataReconciliationService.findByRegionCodeAndCdBatch("up_data_catalog_item",
            // old_region_code,
            // cdBatch);
            // if (udr_list != null && udr_list.size() > 0) {
            // UpDataReconciliation udr = udr_list.get(0);
            // udr.setCdCount(String.valueOf(Integer.parseInt(udr.getCdCount()) -
            // item_size));
            // udr.setUpdateTime(now);
            // udr.setCdTime(now);
            // upDataReconciliationService.update(udr);
            // upDataReconciliationService.update(udr);
            // }

            // udr_list =
            // upDataReconciliationService.findByRegionCodeAndCdBatch("up_data_catalog",
            // region_code,
            // cdBatch);
            // if (udr_list != null && udr_list.size() > 0) {
            // UpDataReconciliation udr = udr_list.get(0);
            // udr.setCdCount(String.valueOf(Integer.parseInt(udr.getCdCount()) + 1));
            // udr.setUpdateTime(now);
            // udr.setCdTime(now);
            // upDataReconciliationService.update(udr);
            // } else {
            // UpDataReconciliation udr = new UpDataReconciliation();
            // udr.setId(reconclition_maxId++);
            // udr.setRegionCode(region_code);
            // udr.setCdBatch(cdBatch);
            // udr.setCdCount("1");
            // udr.setTableName("up_data_catalog");
            // udr.setCdTime(now);
            // udr.setUpdateTime(now);
            // upDataReconciliationService.save(udr);
            // }

            // udr_list =
            // upDataReconciliationService.findByRegionCodeAndCdBatch("up_data_catalog_item",
            // region_code,
            // cdBatch);
            // if (udr_list != null && udr_list.size() > 0) {
            // UpDataReconciliation udr = udr_list.get(0);
            // udr.setCdCount(String.valueOf(Integer.parseInt(udr.getCdCount()) +
            // item_size));
            // udr.setUpdateTime(now);
            // udr.setCdTime(now);
            // upDataReconciliationService.update(udr);
            // } else {
            // UpDataReconciliation udr = new UpDataReconciliation();
            // udr.setId(reconclition_maxId++);
            // udr.setRegionCode(region_code);
            // udr.setCdBatch(cdBatch);
            // udr.setCdCount(String.valueOf(item_size));
            // udr.setTableName("up_data_catalog_item");
            // udr.setCdTime(now);
            // udr.setUpdateTime(now);
            // upDataReconciliationService.save(udr);
            // }

            // }

            result.put("code", 0);
            result.put("msg", "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "更新失败: " + e.getMessage());
        }

        return result;
    }

    @PostMapping("/reupload")
    @ResponseBody
    public Map<String, Object> reuploadCatalogAndItems(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String extCataId = UUID.randomUUID().toString();

        try {

            // 从请求参数中构建UpDataCatalog对象
            UpDataCatalog catalog = new UpDataCatalog();

            // 生成批次号
            int cd_num = 2;
            String cdBatch = DateUtils.generateCdBatch(cd_num);
            String regionCode = request.getParameter("regionCode");

            String updateCycle = request.getParameter("updateCycle");
            String otherUpdateCycle = request.getParameter("otherUpdateCycle");
            if ("8".equals(updateCycle) && (otherUpdateCycle == null || otherUpdateCycle.trim().isEmpty())) {
                result.put("code", 1);
                result.put("msg", "更新周期为其他时，其他更新周期不能为空！");
                return result;
            }

            String pocessLevel = request.getParameter("pocessLevel");
            System.out.println(pocessLevel);
            if (pocessLevel == null || pocessLevel.trim().isEmpty()) {
                result.put("code", 1);
                result.put("msg", "处理级别不能为空！");
                return result;
            }

            String sourceItemName = request.getParameter("sourceItemName");
            if ("null".equals(sourceItemName.trim())) {
                sourceItemName = null;
            }
            String sourceItemCode = request.getParameter("sourceItemCode");
            if ("null".equals(sourceItemCode.trim())) {
                sourceItemCode = null;
            }
            String taskCatalogName = request.getParameter("taskCatalogName");
            if ("null".equals(taskCatalogName.trim())) {
                taskCatalogName = null;
            }
            String taskCatalogCode = request.getParameter("taskCatalogCode");
            if ("null".equals(taskCatalogCode.trim())) {
                taskCatalogCode = null;
            }

            catalog.setId(upDataCatalogService.findMaxId() == null ? 1 : upDataCatalogService.findMaxId() + 1);
            catalog.setBaseCataId(request.getParameter("baseCataId"));
            catalog.setExtCataId(extCataId);
            catalog.setExtCataTitle(request.getParameter("extCataTitle"));
            catalog.setBusinessGroupName(request.getParameter("businessGroupName"));
            catalog.setExtCataCode(request.getParameter("extCataCode"));
            catalog.setFieldType(request.getParameter("fieldType"));
            catalog.setFieldTypeName(request.getParameter("fieldTypeName"));
            catalog.setTaskCatalogName(taskCatalogName);
            catalog.setTaskCatalogCode(taskCatalogCode);
            catalog.setUseLevel(request.getParameter("useLevel"));
            catalog.setDescription(request.getParameter("description"));
            catalog.setExtDataCataCode(request.getParameter("extDataCataCode"));
            catalog.setSharedCondition(request.getParameter("sharedCondition"));
            catalog.setSourceItemName(sourceItemName);
            catalog.setSourceItemCode(request.getParameter("sourceItemCode"));
            catalog.setRelationItemName(request.getParameter("relationItemName"));
            catalog.setRelationItemCode(request.getParameter("relationItemCode"));
            catalog.setImportanceLevel(request.getParameter("importanceLevel"));
            catalog.setPocessLevel(pocessLevel);
            catalog.setAeraScope(request.getParameter("aeraScope"));
            catalog.setOtherAeraScope(request.getParameter("otherAeraScope"));
            catalog.setTimeRange(request.getParameter("timeRange"));
            catalog.setInternalOrgName(request.getParameter("internalOrgName"));
            catalog.setOrgCode(request.getParameter("orgCode"));
            catalog.setExtDescription(request.getParameter("extDescription"));
            catalog.setUpdateCycle(updateCycle);
            catalog.setOtherUpdateCycle(otherUpdateCycle);
            catalog.setIsPublish(request.getParameter("isPublish"));
            catalog.setNotPublishReason(request.getParameter("notPublishReason"));
            catalog.setRegionName(request.getParameter("regionName"));
            catalog.setRegionCode(regionCode);
            catalog.setCatalogType(request.getParameter("catalogType"));
            catalog.setExtCataVersion(request.getParameter("extCataVersion"));
            catalog.setStatus(request.getParameter("status"));
            catalog.setCdBatch(cdBatch);

            Date now = new Date();
            catalog.setCreateTime(now);
            catalog.setUpdateTime(now);
            catalog.setCdTime(now);

            upDataCatalogService.save(catalog);

            int item_num = 0;
            // 处理信息项
            List<UpDataCatalogItem> items = parseCatalogItems(request);
            if (!items.isEmpty()) {
                item_num = items.size();
                int columnMaxId = upDataCatalogItemService.findMaxId() == null ? 1
                        : upDataCatalogItemService.findMaxId() + 1;
                for (UpDataCatalogItem item : items) {
                    item.setId(columnMaxId++);
                    item.setExtCataId(extCataId);
                    item.setColumnId(UUID.randomUUID().toString());
                    item.setCdTime(now);
                    item.setCdBatch(cdBatch);
                    upDataCatalogItemService.insert(item);
                }
            }

            int reconclition_maxId = upDataReconciliationService.findMaxId() == null ? 1
                    : upDataReconciliationService.findMaxId() + 1;
            List<UpDataReconciliation> udcr_result = upDataReconciliationService
                    .findByRegionCodeAndCdBatch("up_data_catalog",
                            regionCode == null ? null : regionCode.toString(), cdBatch);
            if (udcr_result != null && udcr_result.size() > 0) {
                UpDataReconciliation up_udcr = udcr_result.get(0);
                up_udcr.setCdCount(String.valueOf(Integer.parseInt(up_udcr.getCdCount() + 1)));
                up_udcr.setUpdateTime(new Date());
                up_udcr.setCdTime(new Date());
                upDataReconciliationService.update(up_udcr);
            } else {
                UpDataReconciliation udcr = new UpDataReconciliation();
                udcr.setId(reconclition_maxId++);
                udcr.setRegionCode(regionCode);
                udcr.setCdBatch(cdBatch);
                udcr.setCdCount("1");
                udcr.setTableName("up_data_catalog");
                udcr.setCdTime(new Date());
                udcr.setUpdateTime(new Date());
            }

            if (item_num > 0) {
                udcr_result = upDataReconciliationService
                        .findByRegionCodeAndCdBatch("up_data_catalog_item",
                                regionCode == null ? null : regionCode.toString(), cdBatch);
                if (udcr_result != null && udcr_result.size() > 0) {
                    UpDataReconciliation up_udcr = udcr_result.get(0);
                    up_udcr.setCdCount(String.valueOf(Integer.parseInt(up_udcr.getCdCount() + 1)));
                    up_udcr.setUpdateTime(new Date());
                    up_udcr.setCdTime(new Date());
                    upDataReconciliationService.update(up_udcr);
                } else {
                    UpDataReconciliation udcr = new UpDataReconciliation();
                    udcr.setId(reconclition_maxId);
                    udcr.setRegionCode(regionCode);
                    udcr.setCdBatch(cdBatch);
                    udcr.setCdCount(String.valueOf(item_num));
                    udcr.setTableName("up_data_catalog_item");
                    udcr.setCdTime(new Date());
                    udcr.setUpdateTime(new Date());
                }
            }

            result.put("code", 0);
            result.put("msg", "上报成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "上报失败: " + e.getMessage());
        }

        return result;
    }

    // 辅助方法：安全地获取Integer参数
    private Integer getIntegerParameter(HttpServletRequest request, String paramName) {
        String value = request.getParameter(paramName);
        if (value != null && !value.isEmpty() && !"undefined".equals(value)) {
            try {
                return Integer.parseInt(value);
            } catch (NumberFormatException e) {
            }
        }
        return null;
    }

    // 辅助方法：解析信息项列表
    private List<UpDataCatalogItem> parseCatalogItems(HttpServletRequest request) {
        List<UpDataCatalogItem> items = new ArrayList<>();

        // 解析信息项参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<Integer, UpDataCatalogItem> itemMap = new HashMap<>();

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String paramName = entry.getKey();
            String[] paramValues = entry.getValue();
            if (paramName.startsWith("items[")) {
                int startIndex = paramName.indexOf('[');
                int endIndex = paramName.indexOf(']');

                if (startIndex > 0 && endIndex > startIndex) {
                    try {
                        int itemIndex = Integer.parseInt(paramName.substring(startIndex + 1, endIndex));
                        String fieldName = paramName.substring(endIndex + 2);

                        UpDataCatalogItem item = itemMap.computeIfAbsent(itemIndex, k -> new UpDataCatalogItem());

                        if (paramValues.length > 0 && paramValues[0] != null) {
                            String value = paramValues[0];
                            switch (fieldName) {
                                case "id":
                                    item.setId(Integer.parseInt(value));
                                case "extCataId":
                                    item.setExtCataId(value);
                                case "columnId":
                                    item.setColumnId(value);
                                case "cdBatch":
                                    item.setCdBatch(value);
                                case "nameCn":
                                    item.setNameCn(value);
                                    break;
                                case "columnCode":
                                    item.setColumnCode(value);
                                    break;
                                case "dataFormat":
                                    item.setDataFormat(value);
                                    break;
                                case "shareConditionType":
                                    item.setShareConditionType(value);
                                    break;
                                case "shareCondition":
                                    item.setShareCondition(value);
                                    break;
                                case "systemName":
                                    item.setSystemName(value);
                                    break;
                                case "systemId":
                                    item.setSystemId(value);
                                    break;
                                case "systemGroup":
                                    item.setSystemGroup(value);
                                    break;
                                case "status":
                                    item.setStatus(value);
                                    break;
                            }
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        items.addAll(itemMap.values());
        return items;
    }
}